#include "IvwQtInterface.h"
#include <QDebug>
#include "aikit_biz_api.h"
#include "aikit_biz_config.h"

// Initialize static member
IvwQtInterface* IvwQtInterface::m_instance = nullptr;

IvwQtInterface::IvwQtInterface(QObject *parent) :
    QObject(parent),
    m_isInitialized(false)
{
    m_instance = this;
}

IvwQtInterface::~IvwQtInterface()
{
    cleanup();
    if (m_instance == this) {
        m_instance = nullptr;
    }
}

void IvwQtInterface::staticKeywordDetectedCallback(const char* keyword)
{
    if (m_instance) {
        emit m_instance->keywordDetected(QString::fromUtf8(keyword));
    }
}

void IvwQtInterface::staticErrorCallback(const char* errorMsg)
{
    if (m_instance) {
        emit m_instance->errorOccurred(QString::fromUtf8(errorMsg));
    }
}

bool IvwQtInterface::init(const QString& appID, const QString& apiKey, const QString& apiSecret,
                          const QString& resourcePath, int keywordCount)
{
    if (m_isInitialized) {
        qDebug() << "IvwQtInterface already initialized.";
        return true;
    }

    m_appID = appID;
    m_apiKey = apiKey;
    m_apiSecret = apiSecret;
    m_resourcePath = resourcePath;
    m_keywordCount = keywordCount;

    // AIKIT initialization
    AIKIT::AIKIT_Configurator::builder()
        .app()
            .appID(m_appID.toUtf8().constData())
            .apiSecret(m_apiSecret.toUtf8().constData())
            .apiKey(m_apiKey.toUtf8().constData())
            .workDir("./") // Assuming current working directory for now
            .resDir("/oem/aikit/resource/") // This might need to be configurable
            .cfgFile("")
        .auth()
            .authType(0)
            .ability("e867a88f2") // Hardcoded ability ID from speech_recognizer.cpp
        .log()
            .logLevel(AIKIT::LOG_LVL_VERBOSE)
            .logMode(AIKIT::LOG_FILE)
            .logPath("../log/ivw_aikit.log");

    int ret = AIKIT_Init();
    if (ret != 0) {
        qCritical() << "AIKIT_Init failed:" << ret;
        emit errorOccurred(QString("AIKIT_Init failed: %1").arg(ret));
        return false;
    }

    ret = AIKIT_EngineInit("e867a88f2", nullptr);
    if (ret != 0) {
        qCritical() << "AIKIT_EngineInit failed:" << ret;
        emit errorOccurred(QString("AIKIT_EngineInit failed: %1").arg(ret));
        AIKIT_UnInit();
        return false;
    }

    AIKIT_CustomData customData;
    customData.key = "key_word";
    customData.index = 0;
    customData.from = AIKIT_DATA_PTR_PATH;
    customData.value = (void *)m_resourcePath.toUtf8().constData();
    customData.len = m_resourcePath.toUtf8().length();
    customData.next = nullptr;
    customData.reserved = nullptr;

    ret = AIKIT_LoadData("e867a88f2", &customData);
    if (ret != 0) {
        qCritical() << "AIKIT_LoadData failed:" << ret;
        emit errorOccurred(QString("AIKIT_LoadData failed: %1").arg(ret));
        AIKIT_EngineUnInit("e867a88f2");
        AIKIT_UnInit();
        return false;
    }

    // Simple KWS initialization
    ret = simple_kws_init(m_resourcePath.toUtf8().constData(), m_keywordCount,
                          staticKeywordDetectedCallback, staticErrorCallback);
    if (ret != 0) {
        qCritical() << "simple_kws_init failed:" << ret;
        emit errorOccurred(QString("simple_kws_init failed: %1").arg(ret));
        AIKIT_UnLoadData("e867a88f2", "key_word", 0);
        AIKIT_EngineUnInit("e867a88f2");
        AIKIT_UnInit();
        return false;
    }

    m_isInitialized = true;
    qDebug() << "IvwQtInterface initialized successfully.";
    return true;
}

bool IvwQtInterface::startListening()
{
    if (!m_isInitialized) {
        qWarning() << "IvwQtInterface not initialized. Call init() first.";
        emit errorOccurred("IvwQtInterface not initialized. Call init() first.");
        return false;
    }

    if (simple_kws_start() != 0) {
        qCritical() << "Failed to start KWS listening.";
        emit errorOccurred("Failed to start KWS listening.");
        return false;
    }
    qDebug() << "Started KWS listening.";
    return true;
}

bool IvwQtInterface::stopListening()
{
    if (!m_isInitialized) {
        qWarning() << "IvwQtInterface not initialized.";
        return true; // Consider it stopped if not initialized
    }

    if (simple_kws_stop() != 0) {
        qCritical() << "Failed to stop KWS listening.";
        emit errorOccurred("Failed to stop KWS listening.");
        return false;
    }
    qDebug() << "Stopped KWS listening.";
    return true;
}

void IvwQtInterface::cleanup()
{
    if (!m_isInitialized) {
        return;
    }

    simple_kws_cleanup();
    AIKIT_UnLoadData("e867a88f2", "key_word", 0);
    AIKIT_EngineUnInit("e867a88f2");
    AIKIT_UnInit();

    m_isInitialized = false;
    qDebug() << "IvwQtInterface cleaned up.";
}
